package com.origin.onlinesys.common.shiro.filters;

import com.alibaba.fastjson.JSON;
import com.origin.onlinesys.common.services.IShiroPermissionsService;
import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 *
 * 数据库查询用户权限
 * Created by Administrator on 2015/3/2.
 */
public class DbShiroFilterFactoryBean extends ShiroFilterFactoryBean{
    private static final transient Logger log = LoggerFactory.getLogger(DbShiroFilterFactoryBean.class);

    //配置文件默认配置
    Map<String,String> definitionMap;

    //权限查询service
    @Autowired
    IShiroPermissionsService shiroPermissionsService;

    public void setShiroPermissionsService(IShiroPermissionsService shiroPermissionsService) {
        this.shiroPermissionsService = shiroPermissionsService;
    }

    public IShiroPermissionsService getShiroPermissionsService() {
        return shiroPermissionsService;
    }

    /**
     * 更新权限集合
     */
    public void updatePermissions(){
        Map<String, String> filterChainDefinitionMap = getFilterChainDefinitionMap();
        synchronized (filterChainDefinitionMap){
            //清除之前的数据
            filterChainDefinitionMap.clear();
            //修改数据
            if(shiroPermissionsService != null){
                filterChainDefinitionMap.putAll(loadPermissionsFormDb());
            }
            log.debug(JSON.toJSONString(filterChainDefinitionMap));
            //配置文件默认配置
            filterChainDefinitionMap.putAll(definitionMap);
        }
    }

    /**
     * 数据库加载默认权限
     * @return
     */
    public Map<String, String> loadPermissionsFormDb(){
        Map<String, String> dbfilterChainDefinitionMap = shiroPermissionsService.selectAllAsMap();
        return dbfilterChainDefinitionMap;
    }


    public void setFilterChainDefinitions(String definitions) {
        Ini ini = new Ini();
        ini.load(definitions);
        //did they explicitly state a 'urls' section?  Not necessary, but just in case:
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {
            //no urls section.  Since this _is_ a urls chain definition property, just assume the
            //default section contains only the definitions:
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        definitionMap = section;

        updatePermissions();
    }


}

